package org.flckphoto;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * Useful utility functions that can be used everywhere
 */
public class Util {
	public static final String TAG = "Util";
	public static DisplayMetrics METRICS;
	public static Bitmap optimizeImage(String file) {
		
		Bitmap bm = null;
		byte[] buffer = new byte[1024*16];
		BitmapFactory.Options ops = new BitmapFactory.Options();
		ops.inTempStorage = buffer;
		ops.inDither = true;
		ops.inScaled = true;
		ops.inSampleSize = 1;
		boolean error = false;
		
		//keep looping until we can load the image
		do {
			error = false;
			try {
				bm = BitmapFactory.decodeFile(file, ops);
			}
			catch(OutOfMemoryError e) {
				Log.e(TAG, "Out of memory....attempting to resize");
				
				//resize code
				ops.inSampleSize *= 2;
				error = true;
			}
		} while(error);
		
		return bm;
	}
	
/**
 * Optimizes an image and scales it according to how much memory is available
 * @param image the byte array of the image to optimize
 * @return the optimized Bitmap object
 */
public static Bitmap optimizeImage(byte[] image) {
		
		Bitmap bm = null;
		byte[] buffer = new byte[1024*16];
		BitmapFactory.Options ops = new BitmapFactory.Options();
		ops.inTempStorage = buffer;
		ops.inDither = true;
		ops.inScaled = true;
		ops.inSampleSize = 1;
		boolean error = false;
		
		//keep looping until we can load the image
		do {
			error = false;
			try {
				bm = BitmapFactory.decodeByteArray(image, 0, image.length, ops);
			}
			catch(OutOfMemoryError e) {
				Log.e(TAG, "Out of memory....attempting to resize");
				
				//resize code
				ops.inSampleSize *= 2;
				error = true;
			}
		} while(error);
		
		return bm;
	}

/**
 * Converts dp to pixel
 * @param dp the dp of the current screen
 * @return the converted pixel units
 */
public static int dpToPixels(int dp) {
	int pixels =  (int)(dp * (METRICS.densityDpi/160.0f));
	return pixels;
}
	
}
